package com.jokesoft.supermanager.core.services;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.jokesoft.supermanager.common.dto.PersonDto;
import com.jokesoft.supermanager.common.services.Address;
import com.jokesoft.supermanager.common.services.PersonService;
import com.jokesoft.supermanager.core.entities.AddressEntity;
import com.jokesoft.supermanager.core.entities.PersonEntity;
import com.jokesoft.supermanager.core.repositories.PersonRepository;

@Service
public class PersonServiceImpl implements PersonService {

    @Resource
    PersonRepository personrepo;

    @Override
    public PersonDto addPerson(String firstName, String lastName, String role, List<Address> addressList) {

        PersonEntity person = personrepo.insertPerson(firstName, lastName, role, addressList);

        return personToDto(person);
    }

    @Override
    public List<PersonDto> fetchAllPersons() {

        List<PersonDto> personDtoList = new ArrayList<PersonDto>();

        List<PersonEntity> personList = personrepo.fetchAllPersons();

        for (PersonEntity person : personList) {

            personDtoList.add(personToDto(person));
        }

        return personDtoList;
    }

    private PersonDto personToDto(PersonEntity person) {

        List<Address> addresList = new ArrayList<Address>();

        for (AddressEntity addressEntity : person.getAddressList()) {
            Address address = new Address(addressEntity.getStreet(),
                                          addressEntity.getPostalCode(),
                                          addressEntity.getPostOffice(),
                                          addressEntity.getCountry());
            addresList.add(address);
        }

        return new PersonDto(person.getFirstName(),
                             person.getLastName(),
                             person.getRole(),
                             person.getIdentity(),
                             addresList);
    }

}
